package com.market.quote.interfaces.job;

import com.market.quote.app.manager.marketManager.MarketManager;
import com.market.quote.common.DateUtils;
import com.market.quote.modules.stock.domain.dto.StockInfoDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * @author duweibin
 * @date 2024/4/23
 * @description com.market.quote.interfaces.job
 */
@Service
@Slf4j
public class ProcessQuoteCsvJob {

    public static final int BATCH_SIZE = 2;
    public static final int MARKET_CODE_FLAG = 0;
    public static final int STOCK_CODE_FLAG = 1;
    public static final int STOCK_NAME_FLAG = 2;
    public static final int STOCK_PRICE_FLAG = 3;

    @Value("${market.quote.csv-file-path}")
    private String csvFilePath;

    private final MarketManager marketManager;

    @Autowired
    public ProcessQuoteCsvJob(MarketManager marketManager) {
        this.marketManager = marketManager;
    }

    @Scheduled(cron = "0 0 16 * * ?")
    public void process() {
        String date = DateUtils.formatDate(LocalDate.now());
        Integer dateNum = Integer.valueOf(date);
        String filePath = csvFilePath + date + ".csv";


        List<StockInfoDTO> stockInfoDTOList = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 逐行读取文件内容
            while ((line = reader.readLine()) != null) {
                StockInfoDTO stockInfoDTO = parseStockInfo(line, dateNum);
                if (stockInfoDTO == null) {
                    continue;
                }
                stockInfoDTOList.add(stockInfoDTO);
                if (stockInfoDTOList.size() % BATCH_SIZE == 0) {
                    List<StockInfoDTO> pendingStockInfoList = new ArrayList<>();
                    pendingStockInfoList.addAll(stockInfoDTOList);
                    stockInfoDTOList.clear();
                    marketManager.batchSaveStock(pendingStockInfoList);

                }
            }
        } catch (IOException e) {
            log.error("文件处理错误", e);
        }
        if (!stockInfoDTOList.isEmpty()) {
            List<StockInfoDTO> pendingStockInfoList = new ArrayList<>();
            pendingStockInfoList.addAll(stockInfoDTOList);
            stockInfoDTOList.clear();
            marketManager.batchSaveStock(pendingStockInfoList);
        }
    }

    public StockInfoDTO parseStockInfo(String line, Integer dateNum) {
        StockInfoDTO stockInfoDTO = new StockInfoDTO();
        try {
            String[] parts = line.split(",");
            stockInfoDTO.setMarketCode(Integer.valueOf(parts[MARKET_CODE_FLAG]));
            stockInfoDTO.setStockCode(parts[STOCK_CODE_FLAG]);
            stockInfoDTO.setStockName(parts[STOCK_NAME_FLAG]);
            stockInfoDTO.setDate(dateNum);
            stockInfoDTO.setPrice(new BigDecimal(parts[STOCK_PRICE_FLAG]));
        } catch (Exception e) {
            log.error("parse stock info error,line:{}", line, e);
            return null;
        }
        return stockInfoDTO;
    }
}
